package com.zhudi.excel.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class GenericExcelListener<T> extends AnalysisEventListener<Map<Integer, String>> {

    private static final int BATCH_COUNT = 100;

    private List<Map<String, String>> dataList = new ArrayList<>();

    private Map<Integer, String> headMap;

    @Override
    public void invokeHeadMap(Map<Integer, String> headMap, AnalysisContext context) {
        this.headMap = headMap;
    }

    @Override
    public void invoke(Map<Integer, String> data, AnalysisContext context) {
        Map<String, String> newMap = new HashMap<>();
        data.forEach((k, v) -> newMap.put(headMap.get(k), v));
        dataList.add(newMap);
        for (Map<String, String> dataMap : dataList) {
            System.out.println(dataMap);
        }
        if (dataList.size() >= BATCH_COUNT) {
            saveData();
            dataList.clear();
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        saveData();

        System.out.println("所有数据解析完成");
    }

    private void saveData() {
        System.out.println("开始存储数据...");
        System.out.println("存储数据完成");
    }
}